import { WS_API_URL } from '@/config';
import { toast, uuid } from '@/utils';
import { getUser, setUser } from '@/utils/auth';
import { defineStore } from 'pinia';

export const useSocketStore = defineStore('socket', {
  state: () => ({ connect: false, ws: null as WebSocket | null, id: '' }),

  actions: {
    con() {
      if (this.connect == false && this.ws === null) {
        let user = getUser() || {};

        if (!user.id) {
          user.id = uuid();
          setUser(user);
        }
        this.ws = new WebSocket(WS_API_URL + '?id=' + user.id);
        this.ws.onopen = () => {
          console.log('WebSocket 已连接');
          toast('WebSocket on open');
          this.connect = true;
        };
        this.ws.onclose = err => {
          console.log(err);
          console.log('WebSocket 已关闭');
          toast('WebSocket on close');
          this.connect = false;
          this.ws = null;
        };
        this.ws.onerror = err => {
          console.log(err);
          console.log('WebSocket 出错');
          toast('WebSocket on error 重连中...');
          this.con();
        };
        this.ws.onmessage = event => {
          const { data, type } = event.data;
          switch (type) {
            case '1':
              toast(data);
              break;
            case '2':
              toast(data);
              break;
            default:
              break;
          }
        };
      }
    },
    send(data: any) {
      if (!this.connect || this.ws === null) {
        this.con();
        // 等待 WebSocket 连接成功后再发送数据
        const interval = setInterval(() => {
          if (this.connect && this.ws) {
            this.ws.send(JSON.stringify(data));
            clearInterval(interval);
          }
        }, 100);
      } else {
        this.ws.send(JSON.stringify(data));
      }
    },
  },
});
